﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.ServiceRuntime;
using LoadGenerator;
using System.Data;
using System.Web.Services;
using System.Timers;
using System.Web.Script.Serialization;
using System.Threading;

namespace LoadController
{
    public partial class Monitoring : Page
    {
        protected void Page_Load(object sender, System.EventArgs e)
        {
            DisableCache();
        }

        private void DisableCache()
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
            Response.Cache.SetNoStore();
            Response.AppendHeader("pragma", "no-cache");
        }

        private static string GetPartitionKey(string id)
        {
            if (id.Length > 1)
            {
                return id.Substring(1);
            }
            else
            {
                return String.Empty;
            }
        }


        [WebMethod]
        public static string GetNextResult(int counter,string id)
        {
            string jobPK = GetPartitionKey(id);
            if (jobPK == string.Empty)
            {
                return null;
            }
                        
            var resultContainer = AzureBlobHelper.GetContainerReference(AppSettings.BlobContainer_results);


            if (AzureBlobHelper.CheckBlobExists(resultContainer, jobPK))
            {                                                
                var byteArr = AzureBlobHelper.DownloadBlobToByteArray(resultContainer, jobPK);

                Result currentResult = ResultSerializer.Deserialize(byteArr);
                    
                List<string[]> tempSeries = new List<string[]>();
                  
                for (int i = counter; i < currentResult.ChartSeries.Count; i++)   
                {
                        tempSeries.Add(currentResult.ChartSeries[i]);                   
                }
                
                currentResult.ChartSeries = tempSeries;

                return ResultSerializer.Serialize(currentResult);                
            }
            else
            {
                return null;
            }            
        }

    }

}